<script setup lang="ts">
import { useChannelStore } from '@/stores/channel'
import type { ArticleItem, ArticleResData } from '@/types/data'
import axios from 'axios'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
// //列表赋值
const list = ref<ArticleItem[]>([])
// 1.获取父组件传递的参数
// const props = defineProps<{
//   channelId: number
// }>()
// // 2.通过watch监听channelId的变化
// watch(
//   () => props.channelId,
//   async () => {
//     //发送请求获取文章内容
//     const res = await axios<ArticleResData>({
//       url: 'http://geek.itheima.net/v1_0/articles',
//       params: {
//         channel_id: props.channelId,
//         timestamp: Date.now(),
//       },
//     })
//     console.log(res.data)
//     list.value = res.data.data.results
//   },
//   //默认执行一次
//   { immediate: true },
// )

// pinia改写
const store = useChannelStore()
watch(
  () => store.channelId,
  async () => {
    const res = await axios<ArticleResData>({
      url: 'http://geek.itheima.net/v1_0/articles',
      params: {
        channel_id: store.channelId,
        timestamp: Date.now(),
      },
    })
    console.log(res.data)
    list.value = res.data.data.results
  },
  { immediate: true },
)
// 跳转去详情
const router = useRouter()
const toDetail = (id: string) => {
  router.push({
    path: '/detail',
    query: { id: id },
  })
}
</script>

<template>
  <div class="article-list">
    <div class="article-item" v-for="i in list" :key="i.art_id" @click="toDetail(i.art_id)">
      <p class="title">{{ i.title }}</p>
      <!-- 由于v-if和v-for不能同时使用，所以需要用template包裹起来 -->
      <template v-if="i.cover.type > 0">
        <img v-for="(item, index) in i.cover.images" :key="index" class="img" :src="item" alt="" />
      </template>
      <div class="info">
        <span>{{ i.aut_name }}</span>
        <span>{{ i.comm_count }}</span>
        <span>{{ i.pubdate }}</span>
      </div>
    </div>
  </div>
</template>
